package com.ybfenpan.controller;

import com.ybfenpan.model.Daili;
import com.ybfenpan.utils.ContextUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ybfenpan.controller.core.BaseController;
import com.ybfenpan.model.Member;
import com.ybfenpan.service.DailiService;
import com.ybfenpan.service.MemberService;
import com.ybfenpan.service.ParamWageService;
import com.ybfenpan.utils.CryptUtil;
import com.ybfenpan.utils.MapUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 登录
 */
@Controller
public class RegistController extends BaseController {

    @Resource
    private MemberService memberService;
    @Resource
    private ParamWageService paramWageService;
    @Resource
    private DailiService dailiService;

    /**
     * 注册show
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("registShow.shtml")
    public String list(HttpServletRequest request) throws Exception {

        // 获取list

        Map formMap = getParameterMap(request);

        String recommendLoginName = MapUtil.getString(formMap, "recommendLoginName");
        String fatherLoginName = MapUtil.getString(formMap, "fatherLoginName");

        List dailiList = dailiService.queryForList("select", formMap);
        request.setAttribute("dailiList", dailiList);
        String qu = MapUtil.getString(formMap, "qu");

        request.setAttribute("qu", qu);

        request.setAttribute("recommendLoginName", recommendLoginName);
        request.setAttribute("fatherLoginName", fatherLoginName);


        return "memberRegister";
    }

    @RequestMapping("memberRegister.shtml")
    public String submit(ModelMap model, HttpSession session, HttpServletRequest request) throws Exception {
        Map formMap = getParameterMap(request);
        Member regist = ContextUtil.getMember();
        /*****************验证******************/

        //注册人
        Member register = ContextUtil.getMember();
        boolean result = true;
        //账号
        String loginName = MapUtil.getString(formMap, "loginName");

        if (memberService.executMemberByLoginName(loginName) != null) {
            setMessage(model, "该代理商账号已经存在。");
            result = false;
        }

        if (loginName == null || "".equals(loginName)) {
            setMessage(model, "请输入代理商账号。");
            result = false;
        }

        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(loginName);
        if (matcher.find()) {
            setMessage(model, "登录名不能包含中文。");
            result = false;

        }
        //过滤登录名的特殊字符
        if (loginName.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() != 0) {

            setMessage(model, "该登录名含有特殊字符，请重新填写！");
        }

        if (loginName.length() > loginName.replaceAll(" ", "").length()) {
            setMessage(model, "该登录名含有空格，请重新填写！");
        }

        // 服务中心
        String baodanLoginName = MapUtil.getString(formMap, "centerLoginName");
        Integer centerId = null;
        Member center = null;
        if (!baodanLoginName.equals("") && baodanLoginName != null) {
            center = memberService.executMemberByLoginName(baodanLoginName);
            if (center != null) {
                if (center.getAccountCenter().equals("F")) {
                    setMessage(model, "服务中心编号不正确或者该代理商不是服务中心！");
                    result = false;
                } else {
                    centerId = center.getId();
                }
            } else {
                setMessage(model, "服务中心不存在！");
                result = false;
            }
        } else {
            setMessage(model, "服务中心不能为空！");
            result = false;
        }

        // 接点人
        String fatherLoginName = MapUtil.getString(formMap, "fatherLoginName");
        Integer qu = MapUtil.getInteger(formMap,"qu");
        Integer fatherId = null;

        if (!fatherLoginName.equals("") && fatherLoginName != null) {
            Member father = memberService.executMemberByLoginName(fatherLoginName);
            if (father != null) {

                if (qu == 1) {
                    if (father.getZuoId() != null) {
                        setMessage(model, "该接点人左区已经有人了，如果已经注册，请先报单。");
                        result = false;
                    }
                }
                if (qu == 2) {
                    if (father.getYouId() != null) {
                        setMessage(model, "该接点人右区已经有人了，如果已经注册，请先报单。");
                        result = false;
                    }
                }

                if (father.getAccountActive().equals("F")) {
                    setMessage(model, "该接点人未报单，不能放置在该接点人下面。");
                    result = false;

                }

                fatherId = father.getId();
            } else {
                setMessage(model, "接点人不存在。");
                result = false;

            }
        }

        //推荐人
        String recommendLoginName = MapUtil.getString(formMap, "recommendLoginName");

        Integer recommendId = null;
        Member recommend;
        if (recommendLoginName != null && !recommendLoginName.equals("")) {
            recommend = memberService.executMemberByLoginName(recommendLoginName);
            if (recommend != null) {
                if (recommend.getAccountActive().equals("F")) {
                    setMessage(model, "推荐人未报单。");
                    result = false;
                } else {
                    recommendId = recommend.getId();
                }
            } else {
                setMessage(model, "推荐人不存在。");
                result = false;

            }
        } else {
            setMessage(model, "请输入推荐人");
            result = false;
        }

        String onePsw = MapUtil.getString(formMap, "onePassword");
        if (onePsw.length() < 6) {
            setMessage(model, "一级密码必须大于6位。");
            result = false;
        }


        String twoPsw = MapUtil.getString(formMap, "twoPassword");
        if (twoPsw.length() < 6) {
            setMessage(model, "二级密码必须大于6位。");
            result = false;
        }


        if (!result) {
//            request.setAttribute("recommendLoginName", regist.getLoginName());
            List dailiList = dailiService.queryForList("select", formMap);
            request.setAttribute("dailiList", dailiList);
            request.setAttribute("member", formMap);
            return "member/member/memberAdd";
        }


        String onePassword = CryptUtil.getInstance().encrypt2String(onePsw, CryptUtil.keyStr);

        String twoPassword = CryptUtil.getInstance().encrypt2String(twoPsw, CryptUtil.keyStr);

        Integer dailiId = MapUtil.getInteger(formMap, "dailiId");
        Daili daili=this.dailiService.getByKey(dailiId);
        Member one = new Member();

        one.setLoginName(loginName);
        one.setOnePassword(onePassword);
        one.setTwoPassword(twoPassword);
        one.setRecommendId(recommendId);
//        one.setRegisterId(register.getId());
        one.setDailiId(dailiId);
        one.setCenterId(centerId);
        one.setFatherId(fatherId);
        one.setPayNum(daili.getPayNum().doubleValue());
        one.setQu(qu);
        one.setLevel(dailiId);

        one.setCardNo(MapUtil.getString(formMap, "cardNo"));
        one.setRemark(MapUtil.getString(formMap, "remark"));
        one.setTel(MapUtil.getString(formMap, "tel"));
        one.setPersonName(MapUtil.getString(formMap, "personName"));
        one.setWei(MapUtil.getString(formMap, "wei"));
        one.setQq(MapUtil.getString(formMap, "qq"));

        one.setBankShi(MapUtil.getString(formMap, "bankShi"));
        one.setBankName(MapUtil.getString(formMap, "bankName"));
        one.setBankAddress(MapUtil.getString(formMap, "bankAddress"));
        one.setBankCardNo(MapUtil.getString(formMap, "bankCardNo"));
        one.setBankSheng(MapUtil.getString(formMap, "bankSheng"));
        one.setBankPersonName(MapUtil.getString(formMap, "bankPersonName"));


        memberService.saveOne(one);

        if (result) {
            request.setAttribute("result", result);
            setMessage(model, "注册成功，点击跳转到登录。");
            return "memberRegister";
        }

        return "memberRegister";
    }

    /**
     * loginName检测 ajax
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("ajaxGetMemberByName.shtml")
    @ResponseBody
    public void ajaxGetMemberByName(HttpServletRequest request, HttpServletResponse response) {

        Map formMap = getParameterMap(request);
        String loginName = MapUtil.getString(formMap, "loginName");
        Member member = memberService.executMemberByLoginName(loginName);

        HashMap resultformMap = new HashMap();

        if (member == null) {

            renderSuccess(response, true, resultformMap);
        } else {

            renderSuccess(response, false, resultformMap);

        }

    }

    /**
     * 注册ajax
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("ajaxGetFatherByName.shtml")
    @ResponseBody
    public void ajaxTuFahterAction(HttpServletRequest request, HttpServletResponse response) {

        Object retObj = null;
        Map formMap = getParameterMap(request);
        String fatherLoginName = MapUtil.getString(formMap, "fatherLoginName");
        Member member = memberService.executMemberByLoginName(fatherLoginName);
        String personName = "";
        HashMap resultformMap = new HashMap();
        if (member != null) {
            retObj = member;
            if (member.getZuoId() != null && member.getYouId() != null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，左右区均有人，请重新填写。");
            }

            if (member.getZuoId() != null && member.getYouId() == null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，左区有人，请放在右区。");
            }
            if (member.getZuoId() == null && member.getYouId() != null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，右区有人，请放在左区。");
            }
            if (member.getZuoId() == null && member.getYouId() == null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，左右区都没有人。");
            }

            renderSuccess(response, true, resultformMap);
        } else {

            renderSuccess(response, false, resultformMap);

        }

    }

    /**
     * 注册ajax
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("ajaxGetRecommendByName.shtml")
    @ResponseBody
    public void ajaxTuRecommendAction(HttpServletRequest request, HttpServletResponse response) {

        Object retObj = null;
        Map formMap = getParameterMap(request);
        String recommendLoginName = MapUtil.getString(formMap, "recommendLoginName");
        Member member = memberService.executMemberByLoginName(recommendLoginName);
        String personName = "";
        HashMap resultformMap = new HashMap();
        if (member != null) {
            retObj = member;
            personName = member.getPersonName();
            resultformMap.put("member", member);
            resultformMap.put("personName", personName);

            renderSuccess(response, true, resultformMap);
        } else {


            renderSuccess(response, false, resultformMap);

        }

    }

    /**
     * 服务中心
     *
     * @param request
     * @param response
     */
    @RequestMapping("ajaxGetCenterByName.shtml")
    @ResponseBody
    public void ajaxTuCenterAction(HttpServletRequest request, HttpServletResponse response) {

        Object retObj = null;
        Map formMap = getParameterMap(request);
        String centerLoginName = MapUtil.getString(formMap, "centerLoginName");
        Member member = memberService.executMemberByLoginName(centerLoginName);
        String personName = "";
        HashMap resultformMap = new HashMap();
        if (member != null && member.getHistoryBuyStock() > 0) {

            retObj = member;
            personName = member.getPersonName();
            resultformMap.put("member", member);
            resultformMap.put("personName", personName);
            renderSuccess(response, true, resultformMap);
        } else {

//            resultformMap.put("personName", "该代理商不是报单中心。");
            renderSuccess(response, false, resultformMap);

        }
    }

}
